package com.examples.util;

import com.examples.model.BaseResp;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MessageUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private MessageUtil() {
        MAPPER.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    }

    public static <T> String objectToString(T object) throws CustomException {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.INVALID_PARAM.getResultCode(),
                ResultCodeEnum.INVALID_PARAM.getResultCode(), object.getClass().getSimpleName());
        }
    }

    public static <T> T stringToObject(String jsonStr, Class<T> clazz) throws CustomException {
        try {
            return MAPPER.readValue(jsonStr, clazz);
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.INVALID_PARAM.getResultCode(),
                ResultCodeEnum.INVALID_PARAM.getResultCode(), clazz.getSimpleName());
        }
    }

    /**
     * 构建失败响应体
     * 具体可用错误码参考：https://support.huaweicloud.com/accessg-marketplace/zh-cn_topic_0070649057.html
     *
     * @param code    返回码
     * @param message 错误信息
     * @param variables the variables for the message.
     * @return 构造好的失败返回体
     */
    public static BaseResp failResponse(String code, String message, String... variables) {
        BaseResp result = new BaseResp();
        result.setResultMsg(String.format(message, variables));
        result.setResultCode(code);
        return result;
    }
}
